<?php

namespace app\modules\user\controllers;

use yii;
use yii\web\Controller;
use common\models\Tools;
use common\models\Works;
/**
 * 个人中心主页面
 */
class DefaultController extends Controller
{
    public $enableCsrfValidation=false;
	public $leftmenu;
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        //$this->layout = "/personal";
        //检测登录情况
        if (Yii::$app->user->isGuest) {
            return $this->redirect('/site/login?returnurl=/user/default/index');
        }
        //获取我的作品
        $userid = Yii::$app->user->identity->id;
        
        $data['username'] = Yii::$app->user->identity->username;
        $data['mobile'] = Yii::$app->user->identity->mobile == "" ? "":Tools::hideContactInfo(Yii::$app->user->identity->mobile);
//      $data['email'] = Tools::hideContactInfo(Yii::$app->user->identity->email);
        $data['identity_auth'] = Yii::$app->user->identity->identity_auth;
        $data['operate_info'] = Yii::$app->user->identity->operate_info;
        
        $data['headimg'] = Yii::$app->user->identity->headimg == "" ? '/img/user/default-head.png' :Yii::$app->user->identity->headimg;
        $data['introduce'] = Yii::$app->user->identity->introduce;
        //获取我阅读的记录
        $this->getView()->title = "会员中心";
        $this->layout = "/personal";		
		$this->leftmenu='index';
        return $this->render('index',['data'=>$data,]);
    }
    
    public function actionSetIntroduce(){
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $introduce = Tools::GetSafeParam('introduce', "", 1);
		$data['username'] = Yii::$app->user->identity->username;
		$data['mobile'] = Yii::$app->user->identity->mobile == "" ? "":Tools::hideContactInfo(Yii::$app->user->identity->mobile);
        if($introduce != ""){
            $model = \common\models\User::findOne($userid);
            $model->introduce = $introduce;
            $model->save();
            $this->redirect('/user/default/index');
        }
        $this->layout = "/personal";
		$this->leftmenu='introduce';
        return $this->render('set-introduce',['introduce'=>Yii::$app->user->identity->introduce,'data'=>$data]);
    }
	// public function actionSetIntroduce(){
	//     if (Yii::$app->user->isGuest) {
	//         $output['success'] = 0;
	//         $output['msg'] = "未登录";
	//         Tools::outputjson($output);
	//     }
	//     $userid = Yii::$app->user->identity->id;
	//     $introduce = Tools::GetSafeParam('introduce', "", 1);
	//     if($introduce != ""){
	//         $model = \common\models\User::findOne($userid);
	//         $model->introduce = $introduce;
	//         $model->save();
	//         $this->redirect('/user/default/index');
	//     }
	//     $this->layout = "/personal";
	// 	$this->leftmenu='introduce';
	//     return $this->render('set-introduce',['introduce'=>Yii::$app->user->identity->introduce]);
	// }

    public function actionSetheadimg(){
        $this->getView()->title = "设置头像";
		$data['headimg'] = Yii::$app->user->identity->headimg == "" ? '/img/user/default-head.png' :Yii::$app->user->identity->headimg;
		$this->layout = "/personal";
		$this->leftmenu='setheadimg';
        return $this->render('setheadimg',['data'=>$data]);
    }
    
    /***
     * 实名认证
     * 
     */
    public function actionIdentity(){       
        //检测登录情况
        if (Yii::$app->user->isGuest) {
            return $this->redirect('/site/login?returnurl=/user/default/identity');
        }
        $this->getView()->title = "实名认证";
		$this->layout = "/personal";
		$this->leftmenu='introduce';
        return $this->render('identity');
    }

        /**
     * 头像图片上传
     * url: /user/default/headimgupload
     */
    public function actionHeadimgupload(){
        //检测登录情况
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            Tools::outputjson($output);
        }
        
        $userid = Yii::$app->user->identity->id;
        $image = Tools::GetSafeParam('imgdata', '', 1);
        
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }
        
//        $type = $_FILES["file"]["type"];
//        $size = $_FILES["file"]["size"];
//        if($size > 5*1024*1024){//最大上传5M的图片
//            $data['success'] = 0;
//            $data['msg'] = "文件过大，请先压缩一下";
//            Tools::outputjson($data);
//        }
//        
//        if ($type != "image/png" && $type != "image/jpeg" && $type != "image/pjpeg" && $type != "image/gif"){
//            $data['success'] = 0;
//            $data['msg'] = "格式不对，请上传正常格式的图片".json_encode($_FILES);
//            \common\models\Tools::outputjson($data);
//        }
        
//            $tmpName = $_FILES["file"]["tmp_name"];
//            $fileName = $_FILES["file"]["name"];
//            $extName = substr($fileName, strlen($fileName) - 3);
            $extName = 'png';
            $path = Yii::$app->params['userhead'] . DIRECTORY_SEPARATOR . $userid;
            $path = $path . DIRECTORY_SEPARATOR;
            
            

            //目录不存在的话，创建一个
            \app\components\FileUpload::mkDirIfNotExist($path);

            //要保存到服务器上的文件名
            $result = $path . time() . "." . $extName;

            $save = file_put_contents($result, base64_decode($image));
            
            if($save){
                //去掉前面的".",保存到数据库中的信息
                $result = substr($result, 1, strlen($result));

                $user = \common\models\User::findOne(['id'=>$userid]);
                $user->headimg = $result;
                $user->save();
                
                $data['success'] = 1;
                $data['msg'] = '上传成功';
                $data['url'] = $result;
                \common\models\Tools::outputjson($data);
            }
////            $data['success'] = 0;
////            $data['url'] = $result;
////            \common\models\Tools::outputjson($data);
//            
//            //上传文件，确保文件唯一性
//            if (!file_exists($result)) {
//                move_uploaded_file($tmpName, $result);
//            }
//            //去掉前面的".",保存到数据库中的信息
//            $result = substr($result, 1, strlen($result));
//            
//            $user = \common\models\User::findOne(['id'=>$userid]);
//            $user->headimg = $result;
//            $user->save();
//            
//            $data['success'] = 1;
//            $data['msg'] = '上传成功';
//            $data['url'] = $result;
//            \common\models\Tools::outputjson($data);
    }
    
    
    /***
     * 实名认证图片上传
     * url:/user/default/authimgupload
     */
    public function actionAuthimgupload(){
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        
        $type = $_FILES["authimg"]["type"];
        $size = $_FILES["authimg"]["size"];
        if($size > 10*1024*1024){//最大上传10M的图片
            $data['success'] = 0;
            $data['msg'] = "文件过大，请先压缩一下";
            \common\models\Tools::outputjson($data);
        }
        
        if ($type != "image/gif" && $type != "image/jpeg" && $type != "image/pjpeg"){
            $data['success'] = 0;
            $data['msg'] = "格式不对，请上传正常格式的图片";
            \common\models\Tools::outputjson($data);
        }
        
        if (!is_null($_FILES["authimg"])){
            $tmpName = $_FILES["authimg"]["tmp_name"];
            $fileName = $_FILES["authimg"]["name"];
            $extName = substr($fileName, strlen($fileName) - 3);
            $path = Yii::$app->params['userhead'] . DIRECTORY_SEPARATOR . $userid;
            $path = $path . DIRECTORY_SEPARATOR;

            //目录不存在的话，创建一个
            \app\components\FileUpload::mkDirIfNotExist($path);

            //要保存到服务器上的文件名
            $result = $path . md5_file($tmpName) . "." . $extName;

            //上传文件，确保文件唯一性
            if (!file_exists($result)) {
                move_uploaded_file($tmpName, $result);
            }
            //去掉前面的".",保存到数据库中的信息
            $result = substr($result, 1, strlen($result));
            $data['success'] = 1;
            $data['url'] = $result;
            \common\models\Tools::outputjson($data);
        }
    }
    
    public function actionUploadmusic(){
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $username = Yii::$app->user->identity->username;
        $worksid = Tools::GetSafeParam('worksid', "", 1);
        $authorid = Tools::GetSafeParam('authorid', "", 1);
        $type = $_FILES["music"]["type"];
        $size = $_FILES["music"]["size"];
        if($size > 10*1024*1024){//最大上传10M的图片
            $data['success'] = 0;
            $data['msg'] = "文件过大，请先压缩一下";
            \common\models\Tools::outputjson($data);
        }
                
        if ( $type != "audio/mp3"){
            $data['success'] = 0;
            $data['msg'] = "格式不对，请上传MP3格式的文件";
            \common\models\Tools::outputjson($data);
        }
        
        if (!is_null($_FILES["music"])){
            $tmpName = $_FILES["music"]["tmp_name"];
            $fileName = $_FILES["music"]["name"];
            $extName = substr($fileName, strlen($fileName) - 3);
            $path = Yii::$app->params['worksmusic'] . DIRECTORY_SEPARATOR . $worksid;
            $path = $path . DIRECTORY_SEPARATOR;

            //目录不存在的话，创建一个
            \app\components\FileUpload::mkDirIfNotExist($path);

            //要保存到服务器上的文件名
            $result = $path . md5_file($tmpName) . "." . $extName;

            //上传文件，确保文件唯一性
            if (!file_exists($result)) {
                move_uploaded_file($tmpName, $result);
            }
            //去掉前面的".",保存到数据库中的信息
            $result = substr($result, 1, strlen($result));
            
            $model = new \common\models\WorksMusic();
            $model->worksid = $worksid;
            $model->src = $result;
            $model->w_authorid = $authorid;
            $model->m_author = $username;
            $model->m_authorid = $userid;
            $model->addtime = time();
            $model->save();            
            $data['success'] = 1;
            $data['msg'] = "上传成功！";
            \common\models\Tools::outputjson($data);
        }
    }


    /***
     * 实名认证保存数据
     * url:/user/default/authsave
     */
    public function actionAuthsave(){
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $name = Tools::GetSafeParam('name', "", 1);
        $number = Tools::GetSafeParam('number', "", 1);
        $frontimg = Tools::GetSafeParam('frontimg', "", 1);
        $backimg = Tools::GetSafeParam('backimg', "", 1);
        
        $model = \common\models\User::findOne(['id'=>$userid]);
        $model->identity_name = $name;
        $model->identity_id = $number;
        $model->identity_front = $frontimg;
        $model->identity_back = $backimg;
        $model->identity_auth = 1;
        
        if($model->save()){
            $output['success'] = 1;
            $output['msg'] = "提交成功，等待审核。";
            Tools::outputjson($output);
        }else{
            $output['success'] = 0;
            $output['msg'] = "提交失败：".$model->errors;
            Tools::outputjson($output);
        }
    }
    
    /***
     * 绑定手机
     */
    public function actionMobilebind(){
        $this->layout = "/personal";
        //检测登录情况
        if (Yii::$app->user->isGuest) {
            return $this->redirect('/site/login?returnurl=/user/default/mobilebind');
        }
        
        $mobile = Tools::GetSafeParam('mobile', "", 1);
        $code = Tools::GetSafeParam('code', "", 1);
        $hashcode = Tools::GetSafeParam('hashcode', "", 1);
        if($mobile != "" && $code != "" && $hashcode != ""){
            $string = Tools::decrypt($hashcode, Yii::$app->params['sms_encrypt_key']);
            $decrypt_arr = explode('_', $string);
            if($decrypt_arr[1] != $code){
                echo "验证码错误！";exit;
            }
            $userid = Yii::$app->user->identity->id;
            $model = \common\models\User::findOne([$userid]);
            $model->mobile = $mobile;
            if($model->save()){
                return $this->redirect('/user/default/index');
            }
        }
        
        $this->getView()->title = "绑定手机";
        return $this->render('mobilebind');
    }
    
    public function actionPasswdRetrieve(){
        $this->layout = "/personal";
        
        $mobile = Tools::GetSafeParam('mobile', "", 1);
        $code = Tools::GetSafeParam('code', "", 1);
        $hashcode = Tools::GetSafeParam('hashcode', "", 1);
        $passwd = Tools::GetSafeParam('passwd', "", 1);
        if($mobile != "" && $code != "" && $hashcode != "" && $passwd != ""){
            $string = Tools::decrypt($hashcode, Yii::$app->params['sms_encrypt_key']);
            $decrypt_arr = explode('_', $string);
            if($decrypt_arr[1] != $code){
                echo "验证码错误！";exit;
            }
            $model = \common\models\User::findOne(['mobile'=>$mobile]);
            $model->setPassword($passwd);
            $model->generateAuthKey();
            if($model->save()){
                return $this->redirect('/site/login');
            }
        }
        
        $this->getView()->title = "绑定手机";
		$this->layout = "/loglayout";
        return $this->render('passwdretrieve');
    }
	
	
}
